import React, { useEffect, useState, useMemo, useCallback, useRef } from 'react'
import DataAvailable from '../../../Icon/DataAvailable';
import FailLoad from '../../../Icon/FailLoad';
import { useRequest } from 'ahooks';
import { TextWidget } from '@inbiz/react'
import { getFileTypeIconSvg, InbizIcon } from '@inbiz/utils';
import InfiniteScroll from 'react-infinite-scroller';
import { useSearchUIState } from '../../../../../store/hooks/useSearchUIState';
import { useConfigEventsApi, useSearchPropsState } from '../../../../../store/hooks/useSearchPropsState';
import { useJumpResult } from '../../../../../store/hooks/useJumpResult';
import useTemplate from '../../../../../../SearchResultEngine/preview/common/useTemplate'
import { useInbiz } from '../../../../../store/hooks/useInbiz';
import { useSearchUIDispatch } from '../../../../../store/hooks/useSearchUIDispatch';
import { getSearchData } from '../../../service'
import './index.less'
export default function QuickSearchPanel(props) {
  const { hoverIndex, $loading } = props
  const { selectShowTab, keywords, keyword, customFolderId } = useSearchUIState()
  const { synonymSearch } = useSearchPropsState()
  const { configEvents } = useConfigEventsApi();
  const divRef = useRef(null)
  const updateUIState = useSearchUIDispatch();
  const [view] = useTemplate(selectShowTab?.filepath);
  const inbiz = useInbiz();
  const ListView = view?.ListView;
  const [searchData, $searchData] = useState({ RawList: [] })
  const [pageData, $pageData] = useState({ PageIndex: 0, PageSize: 15 })
  const [hasMore, $hasMore] = useState(true)
  const [interfaceError, $interfaceError] = useState(false)
  const [nodata, $nodata] = useState(true)
  const { data, loading, runAsync, params } = useRequest(async (index, size?: number) => {
    let customSearchWhere = ''
    if (customFolderId) {
      if (selectShowTab?.indexLibraries?.[0].IndexName == 'folder') {
        customSearchWhere += `(folderpath:(${customFolderId}) OR masterfolderpathpath:(${customFolderId}))`;
      } else {
        customSearchWhere += `(filepath:(${customFolderId}) OR masterfilepath:(${customFolderId}))`;
      }
    }
    
    let params = {
      KeyWord: keyword,
      PageIndex: index || 1,
      PageSize: size || 15,
      IndexName: selectShowTab?.indexLibraries?.[0].IndexName,
      SearchWhere: selectShowTab?.resultsSearchCriteria??customSearchWhere,
      IsSynonymSearch: synonymSearch
    }
    if (configEvents.current.onParams) {
      params = (await configEvents.current.onParams(params)) ?? params;
    }

    let res = await (configEvents.current.onRequest || getSearchData)(params)

    if (configEvents.current.onData) {
      res = (await configEvents.current.onData(res)) ?? res;
    }

    return res;

  }, {
    debounceWait: 500,
    manual: true,
    onBefore: () => {
      $hasMore(false)
    },
    onSuccess: () => {
      $hasMore(true)
      $nodata(true)
    },
    onError: () => {
      $hasMore(false)
      $interfaceError(true)
    }
  })

  useEffect(() => {
    $loading(loading)
  }, [loading])

  useEffect(() => {
    if (data && data.Code == 0) {
      $searchData(old => {
        let newData = data
        // if (configEvents?.current?.setDataName) {
        //   newData = configEvents?.current?.setDataName(data)
        // }
        return {
          ...newData,
          RawList: params[0] == 1 ? newData.RawList : [...old.RawList, ...newData.RawList]
        }
      })
      $pageData({
        PageIndex: params[0] || 1,
        PageSize: 15,
      })
      const loadDataLength = 15 * params[0]
      if (loadDataLength < data.Total) {

        $hasMore(true)
      } else {
        $hasMore(false)
      }
      updateUIState({
        quickDataLength: data.Total - 1
      })
    }
    else {
      $hasMore(false)
    }
  }, [data])

  useEffect(() => {
    if (keyword) {
      $searchData({ RawList: [] })
      $nodata(false)
      $hasMore(false)
      $interfaceError(false)
      runAsync(1)
    }
  }, [keyword])
  const dataList = useMemo(() => {
    return searchData.RawList?.map(item => {
      return item.RawData
    })
  }, [searchData.RawList])

  const ListViewComponent = useMemo(() => {
    if (ListView && searchData.RawList.length > 0) {
      return searchData.RawList.map((item, index) => {
        const iconUrl = getFileTypeIconSvg(
          selectShowTab?.indexLibraries?.[0].IndexName == 'folder' ? '.folder' : item.RawData?.filename,
        ) as string;
        return ListView({
          data: item,
          config: {},
          inbiz,
          checked: hoverIndex == index,
          icon: iconUrl,
          dataList,
          closePanel: () => {
            updateUIState({
              showSearchResultPanel: false,
            });
          }
        })
      })
    } else {
      return <span></span>
    }
  }, [searchData, ListView, hoverIndex, dataList])
  // 点击搜索
  const onJumpResult = useJumpResult();
  const onSearch = useCallback(
    () => {
      const newKeys: string[] = keywords || [];
      const searchTxt = newKeys;
      onJumpResult(keyword || '', searchTxt, undefined, {
        currentValue: keyword || '',
        isResultButton: false
      });
      updateUIState({
        showSearchResultPanel: false,
        keywords: keyword ? [keyword] : [],
        showGraph: false,
        keyword: keyword,
      });
    },
    [onJumpResult, updateUIState, keywords, keyword],
  );

  return (
    <div className='quickSearchPanel' style={{ height: 500 }}>
      {interfaceError ? (
        <div className='loadError'>
          <FailLoad />
          <div className='loadError_word'><TextWidget>SearchEngine.loadingFail</TextWidget></div>
        </div>
      ) : (
        data?.Total == 0 && nodata ? (
          <div className='viewNoData'>
            <DataAvailable />
            <div className='viewNoData_word'><TextWidget>SearchEngine.noSearchData</TextWidget></div>
          </div>
        ) : (
          <div>
            {/* <div className='viewSearch' onClick={onSearch}>
              <InbizIcon type='icon-chakansuoyoudesousuojieguo' style={{ fontSize: 16 }} className='all-search-view' />
              <span className='all-search-result' >
                <TextWidget>SearchEngine.checkout</TextWidget>
                "{keyword && keyword.length > 27 ? `${keyword.slice(0, 27)}...` : keyword}"
                <TextWidget>SearchEngine.allResults</TextWidget></span>
            </div> */}
            <div className='scrollContainer' ref={divRef}>
              <InfiniteScroll
                className='quickSearchPanel_scroll'
                pageStart={0}
                loadMore={() => {
                  if (hasMore) {
                    return runAsync(pageData.PageIndex + 1)
                  }
                }}
                getScrollParent={() => divRef.current}
                hasMore={hasMore}
                initialLoad={false}
                useWindow={false}
                threshold={32}
              >
                {ListViewComponent}
              </InfiniteScroll>
            </div>
          </div>
        )
      )}
    </div >
  )
}
